//
//  RFAdBannerView.swift
//  RFAds
//
//  Created by Roffa Zhou on 2023/2/17.
//

import Foundation
import GoogleMobileAds

public class RFAdBanner: NSObject {
    //广告单元ID，默认为测试环境ID
    public static var unitId = "ca-app-pub-3940256099942544/2934735716"
    //广告显示的vc页
    public weak var rootVc: UIViewController?
    public var isLoadingAd = false   //是否正在加载广告
    public private(set) var loadedCount: Int = 0       //app生命周期内，加广告成功的次数
    public private(set) var loadCount: Int = 0       //app生命周期内，加载广告的次数, 只要发起了load就算一次

    public var loadedCallback: (()->Void)?  //广告已加载成功回调
    public var loadErrCallback: ((NSError)->Void)?  //广告加载失败回调
    
    public private(set) lazy var adBannerView: BannerView = {
        //let adSize = AdSizeFromCGSize(CGSize(width: 300, height: 50))   //自定义广告尺寸
        let bannerView = BannerView(adSize: AdSizeBanner)
        bannerView.adUnitID = Self.unitId
        bannerView.rootViewController = rootVc
        bannerView.delegate = self
        return bannerView
    }()
    
    
    /// 加载广告
    /// collapsible: top/bottom, 不传将不开启折叠广告功能
    public func loadBanner(_ collapsible: String? = nil ) {
        guard let rv = rootVc?.view else{
            fatalError("加载banner广告前需要给rootVc赋值")
        }
        if Self.unitId.isEmpty {
            #if DEBUG
            print("banner广告unitId为空，预加载失败，直接返回")
            #endif
            if let cb = loadErrCallback {
                cb(NSError(domain: "banner广告unitId为空，预加载失败，直接返回", code: 1100))
            }
            return
        }
        //支持ipad
        if let window = UIApplication.shared.connectedScenes
            .compactMap({ $0 as? UIWindowScene })
            .first?.windows.first {
            
            let viewWidth = window.frame.width
            adBannerView.adSize = currentOrientationAnchoredAdaptiveBanner(width: viewWidth) //UIScreen.main.bounds.width
        }else {
            let viewWidth = 320.0 //frame.size.width
            adBannerView.adSize = currentOrientationAnchoredAdaptiveBanner(width: viewWidth) //UIScreen.main.bounds.width
           
        }
         isLoadingAd = true
        loadCount += 1
        
        let request = Request()

        if let c = collapsible {
            // Create an extra parameter that aligns the bottom of the expanded ad to
            // the bottom of the bannerView.
            let extras = Extras()
            extras.additionalParameters = ["collapsible" : c]
            request.register(extras)
        }
        adBannerView.load(Request())
        
    }
    
}

extension RFAdBanner: BannerViewDelegate {
    //banner加载成功
    public func bannerViewDidReceiveAd(_ bannerView: BannerView) {
        loadedCount += 1
        self.isLoadingAd = false

        if let cb = loadedCallback{
            cb()
        }

    }
    //banner加载失败
    public func bannerView(_ bannerView: BannerView, didFailToReceiveAdWithError error: Error) {
        self.isLoadingAd = false
        if let cb = loadErrCallback {
            cb(error as NSError)
        }
    }
    //点击广告时调用
    public func bannerViewWillPresentScreen(_ bannerView: BannerView) {
        
    }
    //
    public func bannerViewWillDismissScreen(_ bannerView: BannerView) {
        
    }
    public func bannerViewDidDismissScreen(_ bannerView: BannerView) {
        
    }
    public func bannerViewDidRecordClick(_ bannerView: BannerView) {
        
    }
    public func bannerViewDidRecordImpression(_ bannerView: BannerView) {
        
    }
    
}
